package service

import (
	"errors"
	"gitee.com/lanshiren/miniprogram/app/model"
	"time"
)

// SaveUserOpenID ...
func SaveUserOpenID(openId string) error {
	return model.CreateUser(&model.UsersDO{OpenId: openId, LastBanPoint: time.Now()})
}

// UpdateUserInfo ...
func UpdateUserInfo(openId string, user model.UsersDO) error {
	return model.QueryAndUpdateUser(openId, &user)
}

// GetUserByOpenID ...
func GetUserByOpenID(id string) (model.UsersDO, error) {
	return model.QueryUser(id)
}

// QueryUserByID ...
func QueryUserByID(id uint) (model.UsersDO, error) {
	return model.QueryUserByID(id)
}

// UpdateUserRole ...
func UpdateUserRole(id int, newRole int) error {
	return model.QueryAndUpdateUserRole(id, newRole)
}

// GetContactByPhoneOrNickName ...
func GetContactByPhoneOrNickName(sKey string, roleId int) (*model.UserVO, error) {
	user, err := model.GetUserByNikeNameAndRole(sKey, roleId)
	if err != nil {
		return nil, err
	}
	// not fund
	if user.OpenId == "" {
		user_, err := model.GetUserByPhoneAndRole(sKey, roleId)
		if err != nil {
			return nil, err
		}
		if user_.OpenId == "" {
			return nil, errors.New("not fund")
		} else {
			return &model.UserVO{
				ID:        user_.ID,
				Nickname:  user_.Nickname,
				AvatarUrl: user_.AvatarUrl,
				Phone:     user_.Phone,
				BanStatus: user_.BanStatus,
				RoleId:    user_.RoleId,
			}, nil
		}
	} else {
		return &model.UserVO{
			ID:        user.ID,
			Nickname:  user.Nickname,
			AvatarUrl: user.AvatarUrl,
			Phone:     user.Phone,
			BanStatus: user.BanStatus,
			RoleId:    user.RoleId,
		}, nil
	}
}

// SearchContacts ...
func SearchContacts(param model.SearchUsersParam) (int, []*model.UserVO, error) {
	var contacts []*model.UserVO
	total, userDos, err := model.SearchContactsList(param)
	if err != nil {
		return 0, nil, err
	}
	for _, user := range userDos {
		if user.Nickname != "" {
			contacts = append(contacts, &model.UserVO{
				ID:        user.ID,
				Name:      user.Name,
				Nickname:  user.Nickname,
				Gender:    user.Gender,
				City:      user.City,
				AvatarUrl: user.AvatarUrl,
				Campus:    user.Campus,
				Phone:     user.Phone,
				RoleId:    user.RoleId,
			})
		}
	}
	return total, contacts, nil
}

// ConvertUserDOToVo ...
func ConvertUserDOToVo(do *model.UsersDO) model.UserVO {
	return model.UserVO{
		ID:        do.ID,
		Name:      do.Name,
		Nickname:  do.Nickname,
		Gender:    do.Gender,
		City:      do.City,
		AvatarUrl: do.AvatarUrl,
		Campus:    do.Campus,
		Phone:     do.Phone,
		RoleId:    do.RoleId,
	}
}
